#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Monox
 @Email: 627201584@qq.com
 @FileName: BackEnd.py
 @DateTime: 2023/2/23 16:25
 @SoftWare: PyCharm
"""
import API_foundation as apif
import PySimpleGUI as sg
from datetime import datetime


class GY_API:
    def __init__(self, GYurl, GYappkey, GYsecret, GYsessionkey):
        """
        云授权信息初始化
        """
        self.GYurl = GYurl
        self.GYappkey = GYappkey
        self.GYsecret = GYsecret
        self.GYsessionkey = GYsessionkey
        # print('实例化成功')
    def dedeliverys_get(self, express_no):
        """
        调用发货单详情查询（gy.erp.trade.deliverys.detail.get）接口
        """
        method = "gy.erp.trade.deliverys.detail.get"
        List_key = ["appkey", "sessionkey", "method", "express_no"]
        List_value = [self.GYappkey, self.GYsessionkey, method, express_no]
        dic_data = dict(zip(List_key, List_value))
        pyresponse = apif.GYYexecute(dic_data, self.GYsecret, self.GYurl)
        return pyresponse

    def dedeliverys_history_get(self, express_no):
        """
        调用历史发货单详情查询（gy.erp.trade.deliverys.detail.history.get）接口
        """
        method = "gy.erp.trade.deliverys.detail.history.get"
        List_key = ["appkey", "sessionkey", "method", "express_no"]
        List_value = [self.GYappkey, self.GYsessionkey, method, express_no]
        dic_data = dict(zip(List_key, List_value))
        pyresponse = apif.GYYexecute(dic_data, self.GYsecret, self.GYurl)
        return pyresponse

    def Judgment_empty(self, pyresponse):
        """
        判断是发货单是否存在
        """
        delivery = pyresponse.get("delivery")
        if delivery == None:  # 该物流单号查不到数据，无法数据清洗，并执行日志输出和报错
            return 0
        else:
            return 1

    def Data_clean(self, delivery, remarks, warehousein_code):
        """
        数据清洗
        remarks,warehousein_code 注意必填，可以传空
        """
        type_code = "7001"  # 退货原因
        warehousein_code = warehousein_code  # 仓库代码
        pay_time = delivery.get("pay_time")  # 支付时间
        shop_code = delivery.get("shop_code")  # 店铺代码
        trade_platform_code = delivery.get("platform_code")  # 主表平台单号
        vip_code = delivery.get("vip_code")  # 会员代码
        businessman_code = ""  # 业务员代码
        refund_phase = 1  # 售后阶段 1：买家确认收货前 2：买家确认收货后
        return_type = 1  # 售后类型 1：退货 2：换货 3：补发 4：其他 5：维护
        express_name = delivery.get("express_name")  # 快递名称
        express_num = delivery.get("express_no")  # 快递单号
        receiver_name = delivery.get("receiver_name")  # 收货人姓名
        receiver_mobile = delivery.get("receiver_mobile")  # 收货人手机
        receiver_phone = delivery.get("receiver_phone")  # 收货人电话
        area_list = delivery.get('area_name').split('-') if delivery.get('area_name') else ['', '', '']  # 收货信息省市区
        receiver_province = area_list[0]  # 省
        receiver_city = area_list[1]  # 市
        receiver_district = area_list[2]  # 区
        receiver_address = delivery.get("receiver_address")  # 收货详细地址
        note = remarks  # 退货单备注
        refund_detail = [
            {'pay_type_code': 'zhifubao', 'payment': float(delivery.get('payment') + delivery.get('unpaid_amount')),
             'pay_time': pay_time}]  # 退款明细
        details_list = delivery.get("details")  # 商品明细列表
        item_detail = []  # 退货单需要同步的商品明细，初始化为空
        trade_code_list = []  # 将商品明细行的SO单号保存到列表，最后取第一位SO单号关联退货单

        for details in details_list:  # details为字典
            detail_batch = details.get("detail_batch")
            if detail_batch == None or detail_batch == []:
                # print("没有批次")
                trade_code = details.get("trade_code")  # 商品明细SO单号
                trade_code_list.append(trade_code)  # 将商品明细行的SO单号保存到列表
                platform_code = details.get("platform_code")  # 商品明细平台单号
                qty = int(details.get("qty"))  # 商品明细数量
                batch_code = ""  # 批号
                production_time = ""  # 生产日期
                valid_time = ""  # 有效日期
                warehousing_time = ""  # 入库日期
                item_code = details.get("item_code")  # 商品代码
                sku_code = details.get("sku_code")  # 规格代码
                amount = float(details.get("amount_after"))  # 实际退款金额
                amountAfter = float(details.get("amount_after"))  # 让利后金额
                price = float(amountAfter / qty)  # 实际单价
                List_key = ["platform_code", "item_code", "sku_code", "qty", "price", "amount", "amountAfter",
                         "batch_code", "production_time", "valid_time", "warehousing_time", "note"]
                List_value = [platform_code, item_code, sku_code, qty, price, amount, amountAfter, batch_code,
                         production_time, valid_time, warehousing_time, platform_code]
                dict_data = dict(zip(List_key, List_value))  # 两个列表合并为字典
                item_detail.append(dict_data)
            else:
                # print("有批次")
                for ibatch in detail_batch:  # 遍历批次信息
                    trade_code = details.get("trade_code")  # 商品明细SO单号
                    trade_code_list.append(trade_code)  # 将商品明细行的SO单号保存到列表
                    platform_code = details.get("platform_code")  # 商品明细平台单号
                    qty = int(ibatch.get("qty"))  # 批次明细行数量
                    batch_code = ibatch.get("batchNumber")   # 批号
                    production_time = ibatch.get("productionTime")  # 生产日期
                    valid_time = ibatch.get("validTime")  # 有效日期
                    warehousing_time = ibatch.get("warehousingTime")  # 入库日期
                    item_code = details.get("item_code")  # 商品代码
                    sku_code = details.get("sku_code")  # 规格代码
                    amount = float(details.get("amount_after"))  # 实际退款金额
                    amountAfter = float(details.get("amount_after"))  # 让利后金额
                    price = float(amountAfter / qty)  # 实际单价
                    List_key = ["platform_code", "item_code", "sku_code", "qty", "price", "amount", "amountAfter",
                                "batch_code", "production_time", "valid_time", "warehousing_time", "note"]
                    List_value = [platform_code, item_code, sku_code, qty, price, amount, amountAfter, batch_code,
                                   production_time, valid_time, warehousing_time, platform_code]
                    dict_data = dict(zip(List_key, List_value))  # 两个列表合并为字典
                    item_detail.append(dict_data)


        print(f"函数Data_clean：原退货商品明细 item_detail:{item_detail}")
        item_detailMerge = apif.item_detail_Merge(item_detail)  # item_detail商品明细根据[商品代码+批号+生产日期+到期日期+入库日期]进行排重处理
        print(f"函数Data_clean：排重后商品明细 item_detailMerge:{item_detailMerge}")

        method = "gy.erp.trade.return.add"
        List_key = ["appkey", "sessionkey", "method", "shop_code", "warehousein_code", "vip_code", "trade_code",
                 "trade_platform_code", "businessman_code", "refund_phase", "return_type", "type_code", "express_name",
                 "express_num", "receiver_name", "receiver_mobile",
                 "receiver_phone", "receiver_province", "receiver_city", "receiver_district", "receiver_address",
                 "note", "item_detail", "refund_detail"]
        List_value = [self.GYappkey, self.GYsessionkey, method, shop_code, warehousein_code, vip_code, trade_code_list[0], trade_platform_code,
                 businessman_code, refund_phase, return_type,
                 type_code, express_name, express_num, receiver_name, receiver_mobile, receiver_phone,
                 receiver_province, receiver_city, receiver_district, receiver_address,
                 note, item_detailMerge, refund_detail]
        dict_return_add = dict(zip(List_key, List_value))  # 两个列表合并为字典
        return dict_return_add

    def return_add(self, dict_return_add):
        """
        调用退货单新增（gy.erp.trade.return.add）接口
        """
        pyresponse = apif.GYYexecute(dict_return_add, self.GYsecret, self.GYurl)
        return pyresponse

    def execute_2interface(self, result_empty, dedelivery_response, result_empty_history, dedelivery_response_history, remarks, warehousein_code):
        """
        同时用发货单详细和历史发货单详情 调用退货单新增（gy.erp.trade.return.add）接口
        入参：发货单详情，历史发货单详情，备注，仓库代码
        """
        py_delivery = dedelivery_response.get("delivery")
        py_delivery_history = dedelivery_response_history.get("delivery")
        RGO_code_list = []
        errorDesc_list = []
        if result_empty > 0:  # 最近7天的发货单同步到退货单
            dict_return_add = self.Data_clean(py_delivery, remarks, warehousein_code)
            pyresponse = self.return_add(dict_return_add)
            if pyresponse.get('success') == True:  # 如果同步退货单成功则返回RGO单号
                RGO_code = pyresponse.get("code")  # 读取退货RGO单号
                if RGO_code != None:
                    RGO_code_list.append(RGO_code)
            elif pyresponse.get('success') == False:  # 如果同步退货单失败则返回errorDesc，如：商品编码:010138 为批次商品，参数batch_code、production_time、valid_time、warehousing_time必填
                errorDesc_list.append(pyresponse.get('errorDesc'))
        elif result_empty_history > 0:  # 7天以前的发货单同步到退货单
            dict_return_add = self.Data_clean(py_delivery_history, remarks, warehousein_code)
            pyresponse = self.return_add(dict_return_add)
            if pyresponse.get('success') == True:  # 如果同步退货单成功则返回RGO单号
                RGO_code = pyresponse.get("code")  # 读取退货RGO单号
                if RGO_code != None:
                    RGO_code_list.append(RGO_code)
            elif pyresponse.get('success') == False:  # 如果同步退货单失败则返回errorDesc，如：商品编码:010138 为批次商品，参数batch_code、production_time、valid_time、warehousing_time必填
                errorDesc_list.append(pyresponse.get('errorDesc'))
        if len(RGO_code_list) > 0:  # 如果同步成功则返回success=True和RGO单号
            return dict(success=True, data=RGO_code_list)
        elif len(RGO_code_list) == 0:  # 如果同步失败则返回success=False和errorDesc_list
            return dict(success=False, data=errorDesc_list)

    def returnget(self, express_no):
        """
        查询物流单号，返回total，用于判断平台单号是否重复
        """
        method = "gy.erp.trade.return.get"
        cancel = 0
        detail_flag = False
        List_key = ["appkey", "sessionkey", "method", "express_no", "cancel", "detail_flag"]
        List_value = [self.GYappkey, self.GYsessionkey, method, str(express_no), cancel, detail_flag]
        dic_data = dict(zip(List_key, List_value))  # 两个列表合并为字典
        pyresponse = apif.GYYexecute(dic_data, self.GYsecret, self.GYurl)
        return pyresponse


def GYAPI_main(express_no, remarks, warehousein_code, GYurl, GYappkey, GYsecret, GYsessionkey):
    """
    后端运行代函数
    express_no = '75563909669670'
    remarks = 'beizhu'
    warehousein_code = ''
    GYurl = 'http://v2.api.guanyierp.com/rest/erp_open'
    GYappkey = 'XXX'
    GYsecret = 'XXX'
    GYsessionkey = 'XXX'
    main(express_no, remarks, warehousein_code, GYurl, GYappkey, GYsecret, GYsessionkey)
    """
    backend = GY_API(GYurl, GYappkey, GYsecret, GYsessionkey)
    dedelivery_response = backend.dedeliverys_get(express_no)  # 7天之内搜索该物流单号
    dedelivery_response_history = backend.dedeliverys_history_get(express_no)  # 7天之前搜索该物流单号
    result_empty = backend.Judgment_empty(dedelivery_response)  # 判断7天之内有发货单
    result_empty_history = backend.Judgment_empty(dedelivery_response_history)  # 判断7天之前无发货单
    if result_empty + result_empty_history > 0:
        print(f'函数GYAPI_main：物流单号{express_no}成功查到发货单')
        dict_data = backend.execute_2interface(result_empty, dedelivery_response, result_empty_history,
                                                   dedelivery_response_history, remarks, warehousein_code)
        # dict_data = {success:xx,data:xx}
        if dict_data.get('success') ==True:
            RGO_code_list = dict_data.get('data')
            print(f'函数GYAPI_main：物流单号\'{express_no}\'同步成功，RGO_code_list:{RGO_code_list}')
            logodata = f"成功：物流单号\'{express_no}\'同步成功，退货单为{RGO_code_list}"
            sg.cprint(logodata)  # GUI打印更改到这里使用
            log(logodata)
        elif dict_data.get('success') ==False:
            errorDesc = dict_data.get('data')
            print(f'函数GYAPI_main：物流单号\'{express_no}\'同步失败，errorDesc:{errorDesc}')
            logodata = f"失败：物流单号\'{express_no}\'同步失败，报错为{errorDesc}"
            sg.cprint(logodata)  # GUI打印更改到这里使用
            log(logodata)

    elif result_empty + result_empty_history == 0:
        print(f'函数GYAPI_main：物流单号{express_no}没有查到发货单')
        logodata = f"失败：物流单号\'{express_no}\'系统发货单不存在"
        sg.cprint(logodata)  # GUI打印更改到这里使用
        log(logodata)

def log(logdata):
    """
    003
    日志函数
    """
    with open("log.txt", "a") as log:
        log.write(f'时间:{datetime.now()},日志:{logdata}\n\n')



if __name__ == '__main__':
    express_no = '75563909669670'
    remarks = 'beizhu'
    warehousein_code = ''
    GYurl = 'http://v2.api.guanyierp.com/rest/erp_open'
    GYappkey = 'XXX'
    GYsecret = 'XXX'
    GYsessionkey = 'XXX'
    GYAPI_main(express_no, remarks, warehousein_code, GYurl, GYappkey, GYsecret, GYsessionkey)
